package hello;

import java.sql.*;

public class DB {
    String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String dbURL="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=订票系统数据库";
    String userName="sa";
    String userPwd="csl20000617d";
    Connection con;
    ResultSet rs=null;
    Statement stmt;
    public void init() {

        try{Class.forName(driverName);
            System.out.println("加载驱动成功");
        } catch(Exception e){e.printStackTrace();}
        try{
            con=DriverManager.getConnection(dbURL,userName,userPwd);
            System.out.println("连接数据库成功！");
            stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

        }catch(Exception e)
        {
            e.printStackTrace();
            System.out.print("SQL Server连接失败！");
        }
    }

    public ResultSet executeQuery(String sql) {
        try {
            rs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    public int executeUpdate(String sql) {
        int result=0;
        try {
            result=stmt.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void close() {
        try {
            if(rs!=null) rs.close();
            if(stmt!=null) stmt.close();
            if(con!=null) con.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}
